package com.ztgf.order.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.mapper.OrderAfterShipMapper;
import com.ztgf.order.mapper.OrderReturnCommodityMapper;
import com.ztgf.order.models.bo.LogisticsEditBO;
import com.ztgf.order.models.bo.OrderAfterShipSaveBO;
import com.ztgf.order.models.bo.OrderReturnExpirationDateSaveBO;
import com.ztgf.order.models.constant.OrderExpireTimeConstant;
import com.ztgf.order.models.dto.OrderAfterShipDTO;
import com.ztgf.order.models.dto.OrderReturnCommodityDTO;
import com.ztgf.order.models.service.IOrderAfterShipService;
import com.ztgf.order.models.service.IOrderReturnExpirationDateService;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.shopping.models.vo.shop.ShopInfoVO;
import com.ztgf.sms.models.bo.SmsInfoSaveBO;
import com.ztgf.sms.models.service.ISmsInfoService;
import com.ztgf.sys.models.dto.SysDictDTO;
import com.ztgf.sys.models.service.ISysDictService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ztgf.common.utils.UtilConstants.*;

/**
 * author: chenyu.wang
 * date: 2020-06-30 16:22
 * Description:售后订单发货表
 */
@Slf4j
@DubboService
@Lazy
public class OrderAfterShipServiceImpl extends ServiceImpl<OrderAfterShipMapper, OrderAfterShipDTO> implements IOrderAfterShipService {

    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private OrderReturnCommodityMapper orderReturnCommodityMapper;
    @Autowired
    private IOrderReturnExpirationDateService orderReturnExpirationDateService;
    @DubboReference
    private ISysDictService sysDictService;
    @DubboReference
    private IShopInfoService shopInfoService;
    @DubboReference
    private ISmsInfoService smsInfoService;


    @Override
    public Result<List<String>> addOrderShip(OrderAfterShipSaveBO bo) {
        if (bo.getUserType() == 0) {
            return this.buyersShip(bo);//买家发货
        } else {
            return this.sellerShip(bo);//卖家发货
        }
    }

    @Override
    public Result saveOrderShip(OrderAfterShipSaveBO bo) {
        Result result = new Result();
        //验证卖家发货
        Long id = bo.getId();
        if(id == null || id.equals(0L)){
            id = ymlConfig.getPkId();
        }
        OrderAfterShipDTO dto = new OrderAfterShipDTO();
        dto.setId(id);
        dto.setCreateUserId(bo.getCreateUserId());//店铺id
        dto.setOrderId(bo.getOrderId());//订单id
        dto.setLogisticsCompany(bo.getLogisticsCompany());//物流公司名称
        dto.setCompanyCode(bo.getCompanyCode());//物流公司编码
        dto.setShipmentNumber(bo.getShipmentNumber());//物流单号
        dto.setShipWay(bo.getShipWay());//发货方式
        dto.setDeparture(bo.getDeparture());//出发地
        dto.setDestination(bo.getDestination());//目的地
        //保留收货人手机号后四位
        if (!TextUtils.isEmpty(bo.getLastFourPhoneNumber()) && bo.getLastFourPhoneNumber().length() >= 4) {
            dto.setLastFourPhoneNumber(bo.getLastFourPhoneNumber().substring(0, 4));
        }
        dto.setType(bo.getType());
        boolean flag = this.updateById(dto);
        if (!flag) {
            flag = this.insert(dto);
            if(!flag){
                result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
                result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
                return result;
            }
        } else {
            return result;
        }

        int shipState = THREE;
        int afterSalesState = TWO;
        int status = THREE;
        int shopType = bo.getUserType();
        if(shopType == 0){
            shipState = FOUR;
            afterSalesState = TWO;
            status = FOUR;
        }
        OrderReturnCommodityDTO returnCommodityDTO = new OrderReturnCommodityDTO();
        returnCommodityDTO.setId(bo.getOrderId());//退换货表id
        returnCommodityDTO.setShipState(shipState);//3买家待签收
        returnCommodityDTO.setAfterSalesState(afterSalesState);//2售后中
        orderReturnCommodityMapper.updateById(returnCommodityDTO);//修改售后订单状态
        //增加倒计时
        SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.ANNUALFEE_TIME);//待发货倒计时 3天
        String time = sysDictDTO.getValue();
        Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间
        Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(time));//过期时间
        OrderReturnExpirationDateSaveBO expirationDateDTO = new OrderReturnExpirationDateSaveBO();
        expirationDateDTO.setOrderReturnId(bo.getOrderId());//退换货表id
        expirationDateDTO.setStatus(status);//4卖家待签收
        expirationDateDTO.setShopType(shopType);//买家
        expirationDateDTO.setExpirationTime(expireTime);
        orderReturnExpirationDateService.addCheck(expirationDateDTO);
        this.sendSMS(bo.getOrderId());//发送短信
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;

    }

    @Override
    public OrderAfterShipDTO getByOrderId(Long orderId) {
        Wrapper<OrderAfterShipDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        return this.selectOne(wrapper);
    }

    @Override
    public List<OrderAfterShipDTO> getListByOrderId(Long orderId) {
        Wrapper<OrderAfterShipDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        return this.selectList(wrapper);
    }

    @Override
    public OrderAfterShipDTO queryById(Long id) {
        return this.selectById(id);
    }

    @Override
    public Result updateLogistics(LogisticsEditBO saveBO) {
        OrderAfterShipDTO dto = new OrderAfterShipDTO();
        dto.setId(saveBO.getId());
        dto.setLogisticsCompany(saveBO.getCompanyName());//物流公司名称
        dto.setCompanyCode(saveBO.getCompanyCode());//物流公司编码
        dto.setShipmentNumber(saveBO.getMailNo());//物流单号
        dto.setContactInformation(saveBO.getContactInformation());
        if(updateById(dto)){
            return new Result();
        } else {
            return new Result(CodeEnum.FAIL_100011);
        }
    }

    /**
     * description: 卖家售后发货
     * param: []
     * author: chenyu.wang
     * date: 2020-07-07
     * return: com.ztgf.common.constant.Result<java.util.List<java.lang.String>>
     */
    @Transactional
    public Result<List<String>> sellerShip(OrderAfterShipSaveBO bo) {
        Result<List<String>> result = new Result<>();
        //验证卖家发货
        Wrapper<OrderAfterShipDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", bo.getUserType());
        OrderAfterShipDTO shipDTO = this.selectOne(wrapper);
        if (shipDTO != null) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getMsg());
            return result;
        }
        //选择物流
        if (bo.getType() == 0) {
            OrderAfterShipDTO dto = new OrderAfterShipDTO();
            dto.setId(ymlConfig.getPkId());
            dto.setCreateUserId(bo.getCreateUserId());//店铺id
            dto.setOrderId(bo.getOrderId());//订单id
            dto.setLogisticsCompany(bo.getLogisticsCompany());//物流公司名称
            dto.setCompanyCode(bo.getCompanyCode());//物流公司编码
            dto.setShipmentNumber(bo.getShipmentNumber());//物流单号
            dto.setShipWay(bo.getShipWay());//发货方式
            dto.setDeparture(bo.getDeparture());//出发地
            dto.setDestination(bo.getDestination());//目的地
            //保留收货人手机号后四位
            if (!TextUtils.isEmpty(bo.getLastFourPhoneNumber()) && bo.getLastFourPhoneNumber().length() >= 4) {
                dto.setLastFourPhoneNumber(bo.getLastFourPhoneNumber().substring(0, 4));
            }
            dto.setType(bo.getType());
            boolean insert = this.insert(dto);
            if (!insert) {
                result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
                result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
                return result;
            }
            OrderReturnCommodityDTO returnCommodityDTO = new OrderReturnCommodityDTO();
            returnCommodityDTO.setId(bo.getOrderId());//退换货表id
            returnCommodityDTO.setShipState(THREE);//3买家待签收
            returnCommodityDTO.setAfterSalesState(TWO);//2售后中
            orderReturnCommodityMapper.updateById(returnCommodityDTO);//修改售后订单状态
            //增加倒计时
            SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.ANNUALFEE_TIME);//待发货倒计时 3天
            String time = sysDictDTO.getValue();
            Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间
            Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(time));//过期时间
            OrderReturnExpirationDateSaveBO expirationDateDTO = new OrderReturnExpirationDateSaveBO();
            expirationDateDTO.setOrderReturnId(bo.getOrderId());//退换货表id
            expirationDateDTO.setStatus(THREE);//4卖家待签收
            expirationDateDTO.setShopType(ZERO);//买家
            expirationDateDTO.setExpirationTime(expireTime);
            orderReturnExpirationDateService.addCheck(expirationDateDTO);
            this.sendSMS(bo.getOrderId());//发送短信
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        } else {
            //自己联系物流
            OrderAfterShipDTO dto = new OrderAfterShipDTO();
            dto.setId(ymlConfig.getPkId());
            dto.setCreateUserId(bo.getCreateUserId());//店铺id
            dto.setOrderId(bo.getOrderId());//订单id
            dto.setLogisticsCompany(bo.getLogisticsCompany());//物流公司名称/送货员姓名
            if (bo.getShipmentNumber() != null) {
                dto.setShipmentNumber(bo.getShipmentNumber());//物流单号
            }
            dto.setContactInformation(bo.getContactInformation());//联系方式
            dto.setShipWay(bo.getShipWay());//发货方式
            dto.setDeparture(bo.getDeparture());//出发地
            dto.setDestination(bo.getDestination());//目的地
            //保留收货人手机号后四位
            if (!TextUtils.isEmpty(bo.getLastFourPhoneNumber()) && bo.getLastFourPhoneNumber().length() >= 4) {
                dto.setLastFourPhoneNumber(bo.getLastFourPhoneNumber().substring(0, 4));
            }
            dto.setType(bo.getType());
            boolean insert = this.insert(dto);
            if (!insert) {
                result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
                result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
                return result;
            }
            OrderReturnCommodityDTO returnCommodityDTO = new OrderReturnCommodityDTO();
            returnCommodityDTO.setId(bo.getOrderId());//退换货表id
            returnCommodityDTO.setShipState(THREE);//3买家待签收
            returnCommodityDTO.setAfterSalesState(TWO);//2售后中
            orderReturnCommodityMapper.updateById(returnCommodityDTO);//修改售后订单状态
            //增加倒计时
            SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.ANNUALFEE_TIME);//待发货倒计时 3天
            String time = sysDictDTO.getValue();
            Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间
            Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(time));//过期时间
            OrderReturnExpirationDateSaveBO expirationDateDTO = new OrderReturnExpirationDateSaveBO();
            expirationDateDTO.setOrderReturnId(bo.getOrderId());//退换货表id
            expirationDateDTO.setStatus(THREE);//3买家待签收
            expirationDateDTO.setShopType(ZERO);//买家
            expirationDateDTO.setExpirationTime(expireTime);
            orderReturnExpirationDateService.addCheck(expirationDateDTO);
            this.sendSMS(bo.getOrderId());//发送短信
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        }
    }

    /**
     * description: 买家售后发货
     * param: []
     * author: chenyu.wang
     * date: 2020-07-07
     * return: com.ztgf.common.constant.Result<java.util.List<java.lang.String>>
     */
    @Transactional
    public Result<List<String>> buyersShip(OrderAfterShipSaveBO bo) {
        Result<List<String>> result = new Result<>();
        //验证买家发货
        Wrapper<OrderAfterShipDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", bo.getUserType());
        OrderAfterShipDTO shipDTO = this.selectOne(wrapper);
        if (shipDTO != null) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getMsg());
            return result;
        }
        //选择物流
        if (bo.getType() == 0) {
            OrderAfterShipDTO dto = new OrderAfterShipDTO();
            List<String> date = new ArrayList<>();
            dto.setId(ymlConfig.getPkId());
            date.add(dto.getId().toString());
            dto.setCreateUserId(bo.getCreateUserId());//店铺id
            dto.setOrderId(bo.getOrderId());//订单id
            dto.setLogisticsCompany(bo.getLogisticsCompany());//物流公司名称
            dto.setCompanyCode(bo.getCompanyCode());//物流公司编码
            dto.setShipmentNumber(bo.getShipmentNumber());//物流单号
            dto.setShipWay(bo.getShipWay());//发货方式
            dto.setDeparture(bo.getDeparture());//出发地
            dto.setDestination(bo.getDestination());//目的地
            //保留收货人手机号后四位
            if (!TextUtils.isEmpty(bo.getLastFourPhoneNumber()) && bo.getLastFourPhoneNumber().length() >= 4) {
                dto.setLastFourPhoneNumber(bo.getLastFourPhoneNumber().substring(0, 4));
            }
            dto.setType(bo.getType());
            boolean insert = this.insert(dto);
            if (!insert) {
                result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
                result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
                return result;
            }
            OrderReturnCommodityDTO returnCommodityDTO = new OrderReturnCommodityDTO();
            returnCommodityDTO.setId(bo.getOrderId());//退换货表id
            returnCommodityDTO.setShipState(FOUR);//4卖家待签收
            returnCommodityDTO.setAfterSalesState(TWO);//2售后中
            orderReturnCommodityMapper.updateById(returnCommodityDTO);//修改售后订单状态
            //增加倒计时
            SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.ANNUALFEE_TIME);//待发货倒计时 3天
            String time = sysDictDTO.getValue();
            Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间
            Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(time));//过期时间
            OrderReturnExpirationDateSaveBO expirationDateDTO = new OrderReturnExpirationDateSaveBO();
            expirationDateDTO.setOrderReturnId(bo.getOrderId());//退换货表id
            expirationDateDTO.setStatus(FOUR);//4卖家待签收
            expirationDateDTO.setShopType(ONE);//卖家
            expirationDateDTO.setExpirationTime(expireTime);
            orderReturnExpirationDateService.addCheck(expirationDateDTO);
            this.sendSMS(bo.getOrderId());//发送短信
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            result.setData(date);
            return result;
        } else {
            //自己联系物流
            OrderAfterShipDTO dto = new OrderAfterShipDTO();
            List<String> date = new ArrayList<>();
            dto.setId(ymlConfig.getPkId());
            date.add(dto.getId().toString());
            dto.setCreateUserId(bo.getCreateUserId());//店铺id
            dto.setOrderId(bo.getOrderId());//订单id
            dto.setLogisticsCompany(bo.getLogisticsCompany());//物流公司名称/送货员姓名
            if (bo.getShipmentNumber() != null) {
                dto.setShipmentNumber(bo.getShipmentNumber());//物流单号
            }
            dto.setContactInformation(bo.getContactInformation());//联系方式
            dto.setShipWay(bo.getShipWay());//发货方式
            dto.setDeparture(bo.getDeparture());//出发地
            dto.setDestination(bo.getDestination());//目的地
            //保留收货人手机号后四位
            if (!TextUtils.isEmpty(bo.getLastFourPhoneNumber()) && bo.getLastFourPhoneNumber().length() >= 4) {
                dto.setLastFourPhoneNumber(bo.getLastFourPhoneNumber().substring(0, 4));
            }
            dto.setType(bo.getType());
            boolean insert = this.insert(dto);
            if (!insert) {
                result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
                result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
                return result;
            }
            OrderReturnCommodityDTO returnCommodityDTO = new OrderReturnCommodityDTO();
            returnCommodityDTO.setId(bo.getOrderId());//退换货表id
            returnCommodityDTO.setShipState(FOUR);//4卖家待签收
            returnCommodityDTO.setAfterSalesState(TWO);//售后中
            orderReturnCommodityMapper.updateById(returnCommodityDTO);//修改售后订单状态
            //增加倒计时
            SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.ANNUALFEE_TIME);//待发货倒计时 3天
            String time = sysDictDTO.getValue();
            Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间
            Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(time));//过期时间
            OrderReturnExpirationDateSaveBO expirationDateDTO = new OrderReturnExpirationDateSaveBO();
            expirationDateDTO.setOrderReturnId(bo.getOrderId());//退换货表id
            expirationDateDTO.setStatus(FOUR);//4卖家待签收
            expirationDateDTO.setShopType(ONE);//卖家
            expirationDateDTO.setExpirationTime(expireTime);
            orderReturnExpirationDateService.addCheck(expirationDateDTO);
            this.sendSMS(bo.getOrderId());//发送短信
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            result.setData(date);
            return result;
        }
    }


    /*
     * @description:发送短信
     * @author: chenyu.wang
     * @date: 2020-09-16
     * @return:
     */
    @Async
    public void sendSMS(Long orderAfterId) {
        OrderReturnCommodityDTO orderReturnCommodityDTO = orderReturnCommodityMapper.selectById(orderAfterId);
        if (orderReturnCommodityDTO != null) {
            List<Long> idList = new ArrayList<>();
            idList.add(orderReturnCommodityDTO.getBuyersShopId());//买家店铺id
            idList.add(orderReturnCommodityDTO.getSellerShopId());//卖家店铺id
            List<ShopInfoVO> users = shopInfoService.getByShopIds(idList);//获取店铺手机号
            if (!isNull(users)) {
                for (ShopInfoVO user : users) {
                    try {
                        SmsInfoSaveBO smsInfoSaveBO = new SmsInfoSaveBO();
                        smsInfoSaveBO.setMobile(user.getMobile());
                        smsInfoService.saveAfterSale(smsInfoSaveBO);//发送短信
                    } catch (Exception e) {
                        log.info("发货发送短信失败!");
                        e.printStackTrace();
                    }
                }
            } else {
                log.info("暂未查询到店铺手机号,发送短信失败!");
            }
        } else {
            log.info("暂未查询到售后订单信息,无法发送短信!");
        }
    }
}
